package com.grandbroad.eim.ui.activities;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easy.west.westclient.Constants;
import com.easy.west.westclient.MainActivity;
import com.easy.west.westclient.api.login.bean.ReturenUser;
import com.easy.west.westclient.api.login.bean.User;
import com.google.gson.Gson;
import com.grandbroad.eim.R;
import com.grandbroad.eim.base.BaseActivity;
import com.grandbroad.eim.entry.PaySuccessBean;
import com.grandbroad.eim.entry.WhcatBean;
import com.grandbroad.eim.utils.CacheUtils;
import com.grandbroad.eim.utils.ToastUtils;
import com.grandbroad.eim.wedgit.CameraPopupWindow;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.orhanobut.hawk.Hawk;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jiguang.net.HttpUtils;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 用户中心界面
 * 根据身份证号码获取生日
 */
public class UserInfoActivity extends BaseActivity implements View.OnClickListener,EasyPermissions.PermissionCallbacks {
    @BindView(R.id.img_back_btn)
    ImageView imgBackBtn;
    @BindView(R.id.tv_toolbar_title)
    TextView tvToolbarTitle;
    @BindView(R.id.tool_bar)
    Toolbar toolBar;
    @BindView(R.id.img_my_avatar)
    ImageView imgMyAvatar;
    @BindView(R.id.ra_my_avatar)
    RelativeLayout raMyAvatar;
    @BindView(R.id.tv_my_nickname)
    TextView tvMyNickname;
    @BindView(R.id.ra_nick_name)
    RelativeLayout raNickName;
    @BindView(R.id.tv_my_id)
    TextView tvMyId;
    @BindView(R.id.ra_id)
    RelativeLayout raId;
    @BindView(R.id.tv_my_turename)
    TextView tvMyTurename;
    @BindView(R.id.ra_turename)
    RelativeLayout raTurename;
    @BindView(R.id.tv_my_sex)
    TextView tvMySex;
    @BindView(R.id.ra_sex)
    RelativeLayout raSex;
    @BindView(R.id.tv_my_birthday)
    TextView tvMyBirthday;
    @BindView(R.id.ra_birthday)
    RelativeLayout raBirthday;
    @BindView(R.id.tv_my_phone)
    TextView tvMyPhone;
    @BindView(R.id.ra_phone)
    RelativeLayout raPhone;
    @BindView(R.id.tv_my_email)
    TextView tvMyEmail;
    @BindView(R.id.ra_email)
    RelativeLayout raEmail;
    @BindView(R.id.tv_my_company)
    TextView tvMyCompany;
    @BindView(R.id.ra_company)
    RelativeLayout raCompany;
    @BindView(R.id.tv_my_department)
    TextView tvMyDepartment;
    @BindView(R.id.ra_department)
    RelativeLayout raDepartment;
    @BindView(R.id.tv_my_position)
    TextView tvMyPosition;
    @BindView(R.id.ra_position)
    RelativeLayout raPosition;
    @BindView(R.id.tv_my_wechat)
    TextView tvMyWechat;
    @BindView(R.id.ra_my_wechat)
    RelativeLayout raMyWechat;
    private User user;
    private CameraPopupWindow popupWindow;
    private String UPDATE_HEAD_URL=Constants.BASE_URL+"users/uploadnewheadphoto";
    private WhcatBean whcatBean;
    //各种修改模式
    public static final String NICKNAME="nickname";
    public static final String PHONE="phone";
    public static final String EMAIL="email";
    public static final String SEX="sex";
    public static final String COMPANY="company";
    public static final String DEPARTMENT="department";
    public static final String POSITION="position";
    @Override
    protected void initview() {
        //如果微信登陆的实体存在
        whcatBean = Hawk.get("wechat");
        user = CacheUtils.getUser();
        tvToolbarTitle.setText("个人中心");
        initsession();
        //pop
        popupWindow = new CameraPopupWindow(this);
        //在微信登陆的状态下 并且作为鼹鼠用户没有自己的头像
        if (whcatBean!=null&&TextUtils.isEmpty(user.getAvatar()))
        {
            x.image().bind(imgMyAvatar,whcatBean.getHeadimgurl());
            //设置用户相关信息
            tvMyNickname.setText(whcatBean.getNickname());
        }
        else
        {
            x.image().bind(imgMyAvatar,user.getAvatar());
            //设置用户相关信息
            tvMyNickname.setText(user.getName());
        }




    }

    private void initsession() {
        setBackBtn(imgBackBtn);
        raMyAvatar.setOnClickListener(this);
        raNickName.setOnClickListener(this);
        raBirthday.setOnClickListener(this);
        raCompany.setOnClickListener(this);
        raCompany.setOnClickListener(this);
        raDepartment.setOnClickListener(this);
        raPhone.setOnClickListener(this);
        raSex.setOnClickListener(this);
        raEmail.setOnClickListener(this);
        raPosition.setOnClickListener(this);

    }

    @Override
    protected void initdata()
    {


    }

    @Override
    protected int setlayout() {
        return R.layout.actvity_userinfo;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.ra_my_avatar:
                check();
                break;
            case R.id.ra_birthday:
                //生日点击
                //最好弹出日期选择框
                break;
            case R.id.ra_company:
                //公司点击
                startTarget(COMPANY);
                break;
            case R.id.ra_position:
                //职位点击
                startTarget(POSITION);
                break;
            case R.id.ra_department:
                //部门点击
                startTarget(DEPARTMENT);
                break;
            case R.id.ra_email:
                //邮箱点击
                startTarget(EMAIL);
                break;
            case R.id.ra_nick_name:
                //昵称点击
                startTarget(NICKNAME);
                break;
            case R.id.ra_phone:
                //手机点击
                startTarget(PHONE);
                break;
            case R.id.ra_sex:
                //性别点击
                startTarget(SEX);
                break;

        }
    }

    /**
     * 检查权限
     */
    private void check() {
        String [] per = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this,per))
        {
            EasyPermissions.requestPermissions(this,"获取读取存储文件权限",30,per);
            return;
        }
        //弹出底部视图
        showBottomview();
    }

    /**
     * 底部视图
     */
    private void showBottomview() {

        popupWindow.showAtLocation(R.layout.actvity_userinfo);
        popupWindow.setBottomItemClickListener(new CameraPopupWindow.onBottomItemClickListener() {
            @Override
            public void click(View view) {
                switch (view.getId())
                {
                    case R.id.li_camera:
                        toCamera();
                        break;
                    case R.id.li_select_pic:
                        toGarlly();
                        break;
                    case R.id.li_cancel:
                        popupWindow.dismiss();
                        break;
                }
            }
        });
    }

    /**
     * 前往相册
     */
    private void toGarlly() {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(this)
                .openGallery(PictureConfig.TYPE_IMAGE)//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                //.theme()//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(1)// 最大图片选择数量 int
                .minSelectNum(1)// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .previewVideo(false)// 是否可预览视频 true or false
                .enablePreviewAudio(false) // 是否可播放音频 true or false
                .isCamera(false)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                .enableCrop(true)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                //.glideOverride(300,300)// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(1,1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                .isGif(false)// 是否显示gif图片 true or false
                //.compressSavePath(getPath())//压缩图片保存地址
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .openClickSound(true)// 是否开启点击声音 true or false
                //.selectionMedia()// 是否传入已选图片 List<LocalMedia> list
                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                .cropCompressQuality(90)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
                .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                .videoQuality(0)// 视频录制质量 0 or 1 int
                .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
                .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
                .recordVideoSecond(15)//视频秒数录制 默认60s int
                .isDragFrame(false)// 是否可拖动裁剪框(固定)
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    /**
     * 单独拍照
     */
    private void toCamera() {
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                .enableCrop(true)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .openClickSound(true)// 是否开启点击声音 true or false
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    /**
     * 前往对应的修改
     * @param company
     */
    private void startTarget(String company) {
        Bundle bundle = new Bundle();
        bundle.putString("mode",company);
        startActivityWithBundle(EditActivity.class,false,bundle);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        showBottomview();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        //未赋予权限
        ToastUtils.show("没有权限不能获取本地图片");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }

    /**
     * 拍照和选择图片的结果返回
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    updateAvatar(selectList);
                    break;
            }
        }
    }

    /**
     * 更新头像
     * @param selectList
     */
    private void updateAvatar(List<LocalMedia> selectList) {
        //只有一个的
        LocalMedia media = selectList.get(0);
        //被剪辑过才上传
        if (media.isCut()) {
            showProgessDialog("上传中");
            //这里上传头像
            String path = media.getCutPath();
            File file = new File(path);
            RequestParams params = new RequestParams(UPDATE_HEAD_URL);
            params.setMultipart(true);
            params.addHeader("userId", CacheUtils.getUser().getId()+"");
            params.addHeader("access_token", CacheUtils.getUser().getAccess_token());
            params.addBodyParameter("file", file);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    User user = new Gson().fromJson(result,User.class);
                    x.image().bind(imgMyAvatar,user.getAvatar());
                    dissmissDialog();
                    //包括裁剪和压缩后的缓存，要在上传成功后调用，注意：需要系统sd卡权限
                    PictureFileUtils.deleteCacheDirFile(UserInfoActivity.this);
                    popupWindow.dismiss();
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    dissmissDialog();
                    popupWindow.dismiss();


                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }

    }
}
